<template>
  <div style="display: flex; flex-direction: column; width: 100%; height: 100%">
    <div style="width: 100%; height: 10%">
      <el-date-picker
        v-model="searchValue"
        type="datetimerange"
        start-placeholder="起始时间"
        end-placeholder="最后时间"
        format="YYYY-MM-DD HH:mm:ss"
        date-format="YYYY/MM/DD ddd"
        time-format="A hh:mm:ss"
        @clear="handleClear"
      />
      <el-button style="float: right; border-color: blue" @click="exportTable1"
        >导出药品销售数据</el-button
      >
      <el-button style="float: right; border-color: blue; margin-right: 10px" @click="exportTable2"
        >导出个人销售数据</el-button
      >
    </div>
    <div style="display: flex; width: 100%; height: 90%">
      <div class="pie1" style="height: 50%; width: 50%"></div>
      <div class="pie2" style="height: 50%; width: 50%"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts'
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import myAxios from '../../axios/myAxios'
import moment from 'moment'
import ExcelJS from 'exceljs'

let myPie1: echarts.ECharts | null = null
let myPie2: echarts.ECharts | null = null

const medicineData = ref<{ value: number; name: string }[]>([])
const staffData = ref<{ value: number; name: string }[]>([])

const initChart = (container: string, data: { value: number; name: string }[], title: string) => {
  const chartDom = document.querySelector(container)
  if (!chartDom) return

  const chart = echarts.init(chartDom)
  const option = {
    color: ['#006cff', '#60cda0', '#ed8884', '#ff9f7f', '#0096ff', '#9fe6b8', '#32c5e9', '#1d9dff'],
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)',
    },
    legend: {
      bottom: '0%',
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        color: 'rgba(0,0,0,1)',
        fontSize: 10,
      },
    },
    series: [
      {
        name: title,
        type: 'pie',
        radius: ['10%', '70%'],
        center: ['50%', '50%'],
        roseType: 'radius',
        label: { fontSize: 10 },
        labelLine: { length: 6, length2: 8 },
        data: data.length > 0 ? data : [{ name: '暂无数据', value: 0 }], // 处理空数据情况
      },
    ],
  }

  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
  return chart
}

const searchValue = ref()
const handleClear = () => {
  searchValue.value = null
}
const myMedicineData = ref()
const myStaffData = ref()
const init = async () => {
  try {
    // 获取并处理销售数据
    const saleRes = await myAxios.get('/sales/list')
    let sales = saleRes.data.data

    if (!searchValue.value) {
      sales = saleRes.data.data
    } else {
      sales = sales.filter((item) => {
        return moment(item.saleDate).isBetween(searchValue.value[0], searchValue.value[1])
      })
    }
    // 处理员工数据
    const userRes = await myAxios.get('/user/list')
    const users = userRes.data.data.records
    const staffSales = sales.reduce((acc: Record<number, number>, sale) => {
      acc[sale.cashierId] = (acc[sale.cashierId] || 0) + sale.finalAmount
      return acc
    }, {})

    staffData.value = users
      .map((user) => ({
        value: staffSales[user.id] || 0,
        name: user.username,
      }))
      .filter((item) => item.value > 0)

    // 处理药品数据
    const [medicineRes, detailRes] = await Promise.all([
      myAxios.get('/medicine/list'),
      myAxios.get('/sales/detail/list'),
    ])
    console.log(sales)
    const medicines = medicineRes.data.data.records
    let details = detailRes.data.data
    details = details.map((item) => {
      if (sales.find((sale) => sale.saleId === item.saleId)) {
        return item
      } else {
        return null
      }
    })
    details = details.filter((item) => item !== null)
    const medSales = details.reduce((acc: Record<number, number>, detail) => {
      acc[detail.medicineId] = (acc[detail.medicineId] || 0) + detail.subtotal
      return acc
    }, {})

    medicineData.value = medicines
      .map((med) => ({
        value: medSales[med.id] || 0,
        name: med.name,
      }))
      .filter((item) => item.value > 0)

    myMedicineData.value = medicineData.value
    myStaffData.value = staffData.value
    myStaffData.value = myStaffData.value.sort((a, b) => b.value - a.value)
    myMedicineData.value = myMedicineData.value.sort((a, b) => b.value - a.value)
    // 渲染图表
    if (myPie1) myPie1.dispose()
    if (myPie2) myPie2.dispose()
    myPie1 = initChart('.pie1', medicineData.value, '药品销售额')
    myPie2 = initChart('.pie2', staffData.value, '个人销售额')
  } catch (error) {
    console.error('数据加载失败:', error)
  }
}

const exportTable1 = () => {
  const workbook = new ExcelJS.Workbook()
  const worksheet = workbook.addWorksheet('Sheet1')
  worksheet.columns = [
    { header: '药品名称', key: 'name', width: 10 },
    { header: '销售额', key: 'value', width: 10 },
  ]
  myMedicineData.value.forEach((rowData) => {
    worksheet.addRow(rowData)
  })
  workbook.xlsx.writeBuffer().then((buffer) => {
    const blob = new Blob([buffer], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = '药品销售详情.xlsx'
    a.click()
  })
}
const exportTable2 = () => {
  const workbook = new ExcelJS.Workbook()
  const worksheet = workbook.addWorksheet('Sheet1')
  worksheet.columns = [
    { header: '员工名称', key: 'name', width: 10 },
    { header: '销售额', key: 'value', width: 10 },
  ]
  myStaffData.value.forEach((rowData) => {
    worksheet.addRow(rowData)
  })
  workbook.xlsx.writeBuffer().then((buffer) => {
    const blob = new Blob([buffer], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = '个人销售详情.xlsx'
    a.click()
  })
}

watch(searchValue, () => {
  init()
})

onMounted(init)
onBeforeUnmount(() => {
  myPie1?.dispose()
  myPie2?.dispose()
})
</script>
